package com.lei.springbootpractice.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String uri = request.getRequestURI();
        HttpSession session = request.getSession(false);

        // 静态资源放行
        if (uri.startsWith("/css/") || uri.startsWith("/js/")) {
            return true;
        }

        // 未登录用户重定向
        if (session == null || session.getAttribute("loggedInUser") == null) {
            if (!uri.equals("/login") && !uri.equals("/register")) {
                response.sendRedirect("/login");
                return false;
            }
            return true;
        }

        // 已登录用户权限校验
        String role = (String) session.getAttribute("userRole");
        if (uri.startsWith("/admin") && !"admin".equals(role)) {
            response.sendError(HttpStatus.FORBIDDEN.value());
            return false;
        }
        if (uri.startsWith("/courier") && !"courier".equals(role)) {
            response.sendError(HttpStatus.FORBIDDEN.value());
            return false;
        }
        return true;
    }
}
